package com.photo.utils;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author hxm
 */
public class FileUtil {

    public static void copyFile(InputStream is, String outPath) {
        try {
            FileOutputStream fos = new FileOutputStream(outPath);
            byte[] b = new byte[1024];
            while ((is.read(b)) != -1) {
                fos.write(b);
            }
            is.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static boolean deleteFolder(String url) {
        File file = new File(url);
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            file.delete();
            return true;
        } else {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                String root = files[i].getAbsolutePath();
                deleteFolder(root);
            }
            file.delete();
            return true;
        }
    }


    public static String read(String path, Integer count) {
        try {
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(path, "r");
            StringBuilder stringBuilder = new StringBuilder();
            int index = 0;
            long len = raf.length();
            if (len != 0L) {
                long pos = len - 1;
                while (pos > 0) {
                    pos--;
                    raf.seek(pos);
                    if (raf.readByte() == '\n') {
                        index++;
                        stringBuilder.append(new String(raf.readLine().getBytes("ISO-8859-1"),"utf-8"));
                        stringBuilder.append("<br>");
                        if (index >= count) {
                            break;
                        }
                    }
                }
            }
            raf.close();
            return stringBuilder.toString();
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 一行一行写
     */
    public static void write(String path, String log) {
        try {
            byte[] bytes = (DateUtils.nowTime() + ":" + log + "\n").getBytes();
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            Path pathFile = Paths.get(path);
            Files.write(pathFile, bytes, StandardOpenOption.APPEND);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
